package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import validation.UserLoginValidation;
import bizlogic.UserManager;
import model.UserDTO;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProcess(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		// TODO Auto-generated method stub
		doProcess(request, response);
	}
	
	protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		RequestDispatcher rd;
		String status = UserLoginValidation.ValidateLogin(request.getParameter("userid"), request.getParameter("password"));

		if (status == "")
		{
			UserManager um = new UserManager();
			
			UserDTO userToCheck = new UserDTO();			
			userToCheck.setUsername((String)request.getParameter("userid"));
			userToCheck.setPassword((String)request.getParameter("password"));
						
			if (um.isLoginDetailsValid(userToCheck))
			{
				HttpSession hs = request.getSession(true);
				userToCheck = um.getUserDetail((String)request.getParameter("userid"));
				hs.setAttribute("user", userToCheck);
				rd = request.getRequestDispatcher("/LoadBooking");
			} else {
				request.setAttribute("errormessage", "CANNOT LOG-ON LAAAR!<br/>Don't know how to write Laaa?");
				rd = request.getRequestDispatcher("Login.jsp");
			}		
		}
		else
		{
			request.setAttribute("errormessage", status);
			rd = request.getRequestDispatcher("Login.jsp");
		}
		rd.forward(request, response);
	}

}
